$(function() {
	// 加载所有部门...
	$.getJSON("admin/department/department!gets", {
		"listAll" : true
	}, function(data, textStatus, jqXHR) {
		var cnar = $("#groups");
		$.each(data, function(index, item) {
			var opt = $("<option></option>");
			opt.val(item.id);
			opt.text(item.name);
			cnar.append(opt);
		});
	});

	$("#groups")
			.change(
					function() {
						if (toggleUser) {
							$("#users").empty();
							var deptId = $(this).val()[0];
							$.getJSON("admin/user/user!bydepartment",{"department.id":deptId,"start":0,"rows":100},function(data){
								$.each(data.rows,function(idx,item){

									var u = $(item);
									var uid = item.username;
									var uname = item.localName;
									var usr = $("<button type='button' style='padding-left:5px;margin-left:5px;' id='btn_"
											+ uid
											+ "'>"
											+ uname
											+ "</button>");
									usr
											.click(
													function() {
														if ($
																.inArray(
																		uid,
																		pusers) == -1) {
															pusers
																	.push(uid);
															var opt = $("<option></option>");
															opt
																	.val(uid);
															opt
																	.text(uname);
															$(
																	"#susers")
																	.append(
																			$(opt));
														}
														return false;
													})
											.button();
									$("#users")
											.append(
													usr);
								});
							});							
						}

					});
	
	$("#rewind").click(function() {
		saveGroup();
	}).button();
	$("#duser").click(function() {
		deleteUser();
	}).button();
});// end of dom ready
function deleteUser() {
	var vids = $("#susers").val();
	if (vids) {
		$.each(vids, function(idx, item) {
			$("#susers option[value='" + item + "']").remove();
			$.each(pusers, function(i, ite) {
				if (ite != undefined && ite == item) {
					pusers[i] = null;
					delete pusers[i];
				}

			});
		});

	}
}

function saveGroup() {
	var name = $("#name").val();
	if (name == null || name == '' || name == undefined) {
		alert("请填写名称");
		return;
	}
	var paramStr = "";
	$.each(pusers, function(idx, item) {
		if (item != undefined) {
			paramStr += "bean.users[" + idx + "].username=" + item + "&";
		}
	});
	paramStr += "bean.name=" + name + "&";
	$.ajax({
		url : "fileflow/group/custom-organization!add",
		type : "post",
		data : encodeURI(paramStr),
		success : function(data, tstaus, jqxhr) {}
	});
}